#include "mainwindow.h"
#include "ui_mainwindow.h"




MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    ui->lineEdit_ipAdress->setText(settings.value("androidIP", "192.168.178.23").toString());

    connect(ui->pushButton_connect, SIGNAL(clicked()), this, SLOT(connect2android()));
    connect(ui->pushButton_disconnect, SIGNAL(clicked()), this, SLOT(disconnectAndroid()));
    connect(ui->pushButton_sendMessage, SIGNAL(clicked()), this, SLOT(sendData()));

    connect(&android, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
            this, SLOT(connectionStateChanged(QAbstractSocket::SocketState)));
    connect(&android, SIGNAL(readyRead()), this, SLOT(receiveData()));


}

MainWindow::~MainWindow()
{
    delete ui;
}



void MainWindow::connectionStateChanged(QAbstractSocket::SocketState state)
{
    switch (state){
    case QAbstractSocket::ConnectingState:
        ui->label_connectionState->setText(tr("Connecting..."));
        break;
    case QAbstractSocket::HostLookupState:
        ui->label_connectionState->setText(tr("Looking for Host"));
        break;
    case QAbstractSocket::ConnectedState:
        ui->label_connectionState->setText(tr("Connected"));
        break;
    case QAbstractSocket::ClosingState:
        ui->label_connectionState->setText(tr("Closing..."));
        break;
    case QAbstractSocket::UnconnectedState:
        ui->label_connectionState->setText(tr("Disconnected"));
        break;
    default:
        ui->label_connectionState->setText(tr("Error"));
        ui->textBrowser_messageView->append(android.errorString());
        qDebug() << "Error state = " << state;
        break;
    }
}


void MainWindow::connect2android(QString androidIP)
{
    android.connectToHost(QHostAddress(androidIP),40001);
}


void MainWindow::sendData(QString msg)
{
    if (android.isOpen()){
        if (android.write((msg+"\n").toAscii()) != -1){
            roundTripTime.start();
            //qDebug() << "Erfolgreich gesendet: " << msg;
            ui->textBrowser_messageView->append("<"+msg);
        }
        else
            qDebug() << "Fehler beim Senden";
    }
}

void MainWindow::receiveData()
{
    QString answer = ">" + android.readAll();
    if (answer.startsWith(">echo:"))
        answer += "  roundtrip time = " + QString::number(roundTripTime.elapsed()) + "ms";

    ui->textBrowser_messageView->append(answer);
}





void MainWindow::connect2android()
{
    QString androidIP = ui->lineEdit_ipAdress->text();
    settings.setValue("androidIP",androidIP);
    connect2android(androidIP);
}

void MainWindow::disconnectAndroid()
{
    qDebug() << "Disconnecting...";
    android.disconnectFromHost();
}

void MainWindow::sendData()
{
    QString msg = ui->lineEdit_testMessage->text();
    sendData(msg);
}
